<template>
	<div class='box'>
		<u-navbar title="秒杀活动详情"></u-navbar>
		<u-alert-tips type="warning" v-if="disabled" :title="promotionStatus | promotionStatus" :show-icon="true">
		</u-alert-tips>
		<div>
			<u-form label-position='top' :model="form" ref="uForm">
				<u-form-item prop="promotionName" label="活动名称">
					<div>
						<u-input maxlength='25' disabled :custom-style="inputStyle" v-model="form.promotionName" />
					</div>
				</u-form-item>
				<div class='select-goods' v-if='!disabled' @click='selectGoods'>
					选择商品
				</div>
				<u-tabs name="hour" active-color="#333" :list="goodsList" :current="current" @change="changeCurrent">
				</u-tabs>
				<!-- 之前选择 商品部分 -->
				<div class='goods-flex'>
					<div class="goods-item" v-for="(item,index) in goodsList[current].list" :key="index">

						<div class='flex goods-box'>
							<div class="goods-name">
								<div class="wes-2">{{item.goodsName}}</div>
								<div>库存：{{item.quantity}}</div>
								<div v-if="item.promotionApplyStatus">
									<u-tag :text='promotionApplyStatus(item.promotionApplyStatus).text'
										:type="promotionApplyStatus(item.promotionApplyStatus).type"></u-tag>
								</div>
							</div>
							<div>
								<div class="goods-price">
									价格：¥ <u-number-box v-model="item.price" :disabled="disabled"></u-number-box>
								</div>
								<div class="delete" @click='form.promotionGoodsList.splice(index,1)'>
									删除
								</div>
							</div>
						</div>
						<u-line color="#ededed" />
					</div>
				</div>
				<!-- 结束 -->
				<u-form-item prop="startTime" label="活动时间-开始">
					<u-input style="width: 100%;" disabled :custom-style="inputStyle" v-model="form.startTime" />
				</u-form-item>
				<u-form-item prop="endTime" label="活动时间-结束">
					<u-input style="width: 100%;" disabled :custom-style="inputStyle" v-model="form.endTime" />
				</u-form-item>

				<div class='submit' v-if='!disabled' @click='submit'>
					保存/提交
				</div>

			</u-form>


		</div>
	</div>
</template>
<script>
	import {
		savePinTuan,
		editPinTuan,
		getSeckillDetail,
		getSeckillGoodsList,
		addSeckillGoodsList
	} from "@/api/promotion";
	import storage from "@/utils/storage.js"; //缓存
	export default {
		data() {
			return {
				current: 0,
				disabled: true, // 表单input禁用状态

				promotionStatus: "", // 活动状态

				form: {
					promotionName: "", // 活动名称
					startTime: "",
					endTime: "",
				},

				submitLoading: false, // 添加或编辑提交状态
				options: {
					// 不可选取时间
					disabledDate(date) {
						return date && date.valueOf() < Date.now() - 86400000;
					},
				},

				inputStyle: {
					background: "#f7f7f7",
					"padding-left": "20rpx",
					"border-radius": "10rpx",
				},
				routerVal: "",
				goodsList: [{
					hour: 0,
					list: [],
				}], // 商品列表
				searchForm: {
					// 搜索框初始化对象
					pageNumber: 0, // 当前页数
					pageSize: 1000, // 页面大小
					seckillId: ''
				},
				hours: '' //存储的时间

			}
		},
		// 必须要在onReady生命周期，因为onLoad生命周期组件可能尚未创建完毕
		onReady() {
			// this.$refs.uForm.setRules(this.rules);
		},
		mounted() {
			this.init();
		},
		onLoad(options) {
			this.routerVal = options
			this.searchForm.seckillId = options.id
		},
		onShow() {
			uni.$on("selectedGoods", res => {
				
				let way = []
				res.forEach(e => {
					way.push({
						goodsName: e.goodsName,
						price: e.price,
						originalPrice: e.price,
						promotionApplyStatus: e.promotionApplyStatus || "",
						quantity: e.quantity,
						seckillId: this.routerVal.id,
						storeId: e.storeId,
						storeName: e.storeName,
						skuId: e.id,
						timeLine: this.hours[this.current].split(':')[0]
					})
				})
				this.goodsList[this.current].list = way
				uni.$off('selectedGoods'); // 清除监听
			})
		},
		methods: {
			// 点击当前tab的回调
			changeCurrent(index) {
				this.current = index
			},
			// 选择商品
			selectGoods() {
				let ids = []
				this.goodsList[this.current].list.forEach(item => {
					if (item) {
						ids.push(item.skuId)
					}
				})
				uni.navigateTo({
					url: `/pages/goods/skuList?selected=1&ids=${ids}`
				})
			},

			// 初始化
			async init() {
				uni.showLoading({
					title: '加载中'
				})
				const res = await getSeckillDetail(
					this.routerVal.id
				)
				uni.hideLoading()
				if (res.data.success) {
					const result = res.data.result

					this.form = res.data.result


					// 初始化tab
					this.hours = this.unixHours(res.data.result.hours);
					this.goodsList = []
					this.hours.forEach((e) => {
						this.goodsList.push({
							hour: e,
							list: [],
						});
					});
					this.seckillGoodsList();

					this.promotionStatus = res.data.result.promotionStatus
					this.disabled = res.data.result.promotionStatus != 'NEW'
				}
			},

			//秒杀活动商品
			async seckillGoodsList() {
				const res = await getSeckillGoodsList(this.searchForm)
				if (res.data.success) {
					let data = res.data.result.records;
					// 未处理时间 为'1'
					let noFilterhours = this.hours;
					console.log(noFilterhours)
					if (data.length) {
						noFilterhours.forEach((e, index) => {
							data.forEach((i) => {
								if (i.timeLine == e.split(':')[0]) {
									this.goodsList[index].list.push(i);
								}
							});
						});
					}
				}
			},


			// 处理小时
			unixHours(item) {
				if (item) {
					// 处理小时场次
					let hourArr = item.split(",");
					for (let i = 0; i < hourArr.length; i++) {
						hourArr[i] += ":00";
					}
					return hourArr;
				}
				return [];
			},

			// 格式化申请状态
			promotionApplyStatus(key) {
				switch (key) {
					case "APPLY":
						return {
							text: '申请',
								type: 'primary'
						};
					case "PASS":
						return {
							text: '通过',
								type: 'success'
						};

					case "REFUSE":
						return {
							text: '拒绝',
								type: 'error'
						};
					default:
						return {
							text: '未申请',
								type: 'info'
						};

				}
			},

			// 修改/保存
			async submit() {
				const list = JSON.parse(JSON.stringify(this.goodsList));
				let params = {
					seckillId: this.routerVal.id,
					data: [],
				};
				list.forEach((e, index) => {
					e.list.forEach((i) => {
						params.data.push(i);
					});
				});
				uni.showLoading({
					title: '加载中'
				})
				const res = await addSeckillGoodsList(params)
				uni.hideLoading()
				if (res.data.success) {
					uni.showToast({
						title: '提交活动商品成功',
						icon: 'none'
					})
					setTimeout(() => {
						uni.navigateBack()
					}, 1000)
				}

			},

		}
	}
</script>
<style scoped lang="scss">
	.box {
		padding: 16rpx;
		padding-bottom: 100rpx;
	}

	.select-goods {
		background: #333;
		color: #fff;
		width: 200rpx;
		height: 60rpx;
		line-height: 60rpx;
		text-align: center;
		border-radius: 10rpx;
		margin: 20rpx 0;
	}

	.goods-item {
		padding: 32rpx 0;
	}

	.goods-price {
		text-align: right;
	}

	.goods-box {
		width: 100%;
	}

	.goods-name {
		flex: 2;
		color: #999;
		margin-left: 20rpx;

		>* {
			margin-bottom: 10rpx;
		}

		>.wes-2 {
			font-size: 30rpx;
			font-weight: bold;
			color: #333;
			margin-bottom: 10rpx;
		}
	}

	.goods-total {
		display: flex;
		flex-direction: column;
		margin-top: 20rpx;

		>.flex {
			justify-content: space-between;
			margin: 10rpx 0;
			line-height: 1.75;

			>div:nth-of-type(1) {
				font-size: 24rpx;
				color: #999;
			}

			>div:nth-of-type(2) {
				font-weight: bold;

				>span {
					font-size: 40rpx;
					margin-left: 10rpx;
				}
			}

			>div {
				margin: 0 4rpx;
				display: flex;
				align-items: center;
				justify-content: flex-end;
			}
		}
	}

	.submit {
		position: fixed;
		bottom: 10rpx;
		width: 90%;
		left: 5%;
		z-index: 99;
	}

	.delete {
		color: $main-color;
		margin: 20rpx 0;
		text-align: right;
	}
</style>
